package com.demo.redis.config;

import com.fasterxml.jackson.databind.JavaType;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.StringUtils;

/**
 * CacheManager配置类
 * @author cyj
 */
public class CacheManagerConfig {

    public static RedisCacheConfiguration getConfig(JavaType javaType) {
        return RedisCacheConfiguration.defaultCacheConfig()
                // key生成策略
                .computePrefixWith(cacheKeyPrefix)
                //如果是空值，不缓存
                .disableCachingNullValues()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer(javaType))));
    }

    /**
     * 根据javaType将纯JSON格式的字符反序列化相应的对象
     * 如果没有javaType，纯JSON格式的字符串反序列化对象是List<LinkedHashMap>
     * @param javaType 对象类型
     * @return redis序列化对象
     */
    private static RedisSerializer<Object> valueSerializer(JavaType javaType) {
        return new Jackson2JsonRedisSerializer<>(javaType);
    }

    /**
     * 定义缓存key规则生成策略
     */
    private final static CacheKeyPrefix cacheKeyPrefix = cacheName -> {
        if (!StringUtils.hasText(cacheName)) {
            return cacheName;
        }

        return StringUtils.endsWithIgnoreCase(cacheName, ":") ? cacheName : cacheName + ":";
    };
}
